<template>
  <el-dialog
    v-model="drawerVisible"
    :destroy-on-close="true"
    :title="`${drawerProps.title}客户跟进`"
    width="44%"
    top="10vh"
    draggable
    custom-class="user-info-dialog"
  >
    <div class="info-container">
      <el-scrollbar height="100%">
        <el-form
          ref="ruleFormRef"
          label-width="100px"
          label-suffix=" :"
          :rules="rules"
          :disabled="drawerProps.isView"
          :model="drawerProps.row"
          :hide-required-asterisk="drawerProps.isView"
          label-position="top"
          class="info-form"
        >
          <el-form-item label="客户公司名称" prop="companyName">
            <el-select
              v-model="drawerProps.row.companyId"
              placeholder="请选择客户公司"
              clearable
              @change="changeCompany"
              :disabled="isDisCompany"
            >
              <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item label="跟进方式" prop="typeId">
            <el-select v-model="drawerProps.row!.typeId" placeholder="请选择跟进方式" clearable>
              <el-option
                v-for="item in drawerProps.dictList[dict.customerFollowing]"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="项目阶段" prop="stageId">
            <el-select v-model="drawerProps.row!.stageId" placeholder="请选择项目阶段" clearable>
              <el-option
                v-for="item in drawerProps.dictList[dict.customerStage]"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户星级" prop="importanceId">
            <el-rate v-model="drawerProps.row!.importanceId" :colors="['#5378F6', '#5378F6', '#5378F6']" />
          </el-form-item>

          <el-form-item label="拜访时间" prop="visitTime">
            <el-date-picker
              v-model="drawerProps.row!.visitTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择拜访时间"
            />
          </el-form-item>
          <el-form-item label="下次拜访时间" prop="nextVisitTime">
            <el-date-picker
              v-model="drawerProps.row!.nextVisitTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择下次拜访时间"
            />
          </el-form-item>
          <el-form-item label="跟进内容" prop="content">
            <el-input type="textarea" v-model="drawerProps.row!.content" placeholder="请填写跟进内容" clearable></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="drawerProps.row!.remark" placeholder="请填写备注" clearable></el-input>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, getCurrentInstance, onMounted, computed } from "vue"; // getCurrentInstance
const cxt = getCurrentInstance();
const dict = cxt?.appContext.config.globalProperties.$dict;
import { ElMessage, FormInstance, CascaderInstance } from "element-plus";
import { User, Dict } from "@/api/interface";
import { getCompanyList } from "@/api/modules/customer";

const cascaderRef = ref<CascaderInstance>();

const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {},
  dictList: {}
});
const rules = reactive({
  avatarUrl: [{ required: true, message: "请上传用户头像" }],
  mobile: [{ required: true, pattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/, message: "请填写手机号" }],
  totalIntegral: [{ required: false, pattern: /^[0-9]+$/, message: "只能为数字" }],
  iceIntegral: [{ required: false, pattern: /^[0-9]+$/, message: "只能为数字" }],
  name: [{ min: 0, max: 10, trigger: "blur", message: "用户名0-10位之间" }],
  email: [{ required: false, message: "请填写邮箱" }],
  password: [
    {
      required: true,
      pattern: /^[A-Za-z0-9]{8,18}$/,
      message: "密码必须由字母、数字组成，区分大小写, 8-18位"
    }
  ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  dictList: Dict.ResDictList;
}

const drawerVisible = ref(false);

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      console.log(drawerProps.value.row!.addressed);
      // 处理意向车型
      if (drawerProps.value.row.companyProductsed && drawerProps.value.row.companyProductsed.length) {
        drawerProps.value.row.companyProducts = drawerProps.value.row.companyProductsed.map(item => {
          const name = drawerProps.value.productModelList.find(itm => itm.id === item);
          return {
            productModelId: item,
            productModelName: name.name,
            productModelPicture: name.picture
          };
        });
      }
      // 省市区传值处理
      if (drawerProps.value.row!.addressed && drawerProps.value.row!.addressed.length) {
        let arrAddress = cascaderRef.value.getCheckedNodes();
        let names = arrAddress[0]["pathLabels"];
        let value = drawerProps.value.row!.addressed;
        drawerProps.value.row.province = names[0];
        drawerProps.value.row.provinceCode = value[0];
        drawerProps.value.row.city = names[1];
        drawerProps.value.row.cityCode = value[1];
        drawerProps.value.row.district = names[2];
        drawerProps.value.row.districtCode = value[2];
      }
      delete drawerProps.value.row.addressed;
      delete drawerProps.value.row.companyProductsed;
      await drawerProps.value.api!(drawerProps.value.row);
      // 处理省市区的传值
      ElMessage.success({ message: `${drawerProps.value.title}客户成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
      // 如果当前编辑是自己
      // if (drawerProps.value.row.id && userStore.userInfo.id === drawerProps.value.row.id) {
      //   mittBus.emit("refreshUserInfo");
      // }
    } catch (error) {
      console.log(error);
    }
  });
};
// 获取全部公司
let companyList = reactive([]);
const getCompanyListFn = async () => {
  const { data } = await getCompanyList();
  companyList = data || [];
};
// 公司
const changeCompany = item => {
  const companyLists = companyList.find(itm => itm.id === item);
  drawerProps.value.row.companyName = companyLists?.name;
  // 带出来状态和重要程度
  drawerProps.value.row.importanceId = companyLists?.importanceId;
};
const isDisCompany = computed(() => {
  return drawerProps.value.title === "编辑" || drawerProps.value.fromMaintenance;
});

onMounted(() => {
  getCompanyListFn();
});
defineExpose({
  acceptParams
});
</script>
<style lang="scss" scoped>
:deep(.user-info-dialog) {
  display: flex;
  height: 600px;
}
.info-container {
  height: 380px;
}
.info-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 0 30px;
  :deep(.el-date-editor) {
    --el-date-editor-width: 100%;
  }
  .el-select,
  .el-cascader,
  .el-date-editor {
    width: 100%;
  }
}
</style>
